package data;
import java.sql.*;
import java.util.*;

public class SectionList {

	private String quarter;
	private int year;
	private Map<Integer, Map<Integer, List<Meeting>>> meetings;
	private Map<Integer, String> classes;

	public SectionList(String quarter, int year) {
		this.quarter = quarter;
		this.year = year;
		this.meetings = new HashMap<Integer, Map<Integer, List<Meeting>>>();
		this.classes = new HashMap<Integer, String>();
		loadSectionsFromDB();
	}

	private void loadSectionsFromDB() {
		// Load Driver class file
		try {
			DriverManager
					.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());

			// Make a connection to the MS SQL database "cse132b"
			Connection conn = DriverManager
					.getConnection(
							"jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName=cse132b",
							"cse132b", "cse132b");

			PreparedStatement pstmt = conn
					.prepareStatement("SELECT c.class_id, s.section_id, course_number, title, weekday, start_time, end_time FROM section s, class c, meeting m WHERE s.class_id = c.class_id "
							+ "AND s.section_id = m.section_id AND c.quarter = ? AND c.year = ?");
			pstmt.setString(1, quarter);
			pstmt.setInt(2, year);

			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				int classId = rs.getInt("class_id");
				int sectionId = rs.getInt("section_id");
				classes.put(
						classId,
						rs.getString("course_number") + " "
								+ rs.getString("title"));
				if (!meetings.containsKey(classId)) {
					meetings.put(classId, new HashMap<Integer, List<Meeting>>());
				}
				if (!meetings.get(classId).containsKey(sectionId)) {
					meetings.get(classId).put(sectionId,
							new LinkedList<Meeting>());
				}
				String[] weekdays = rs.getString("weekday").split(" ");
				String startTime = rs.getString("start_time");
				String endTime = rs.getString("end_time");
				for (String weekday : weekdays) {
					meetings.get(classId).get(sectionId)
							.add(new Meeting(weekday, startTime, endTime));
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public Map<Integer, Map<Integer, List<Meeting>>> getMeetings() {
		return meetings;
	}
	
	public Map<Integer, String> getClasses() {
		return classes;
	}
}
